<?php
/**
 * user相关的service实现
 * @文件名称: GetInfoAction.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\modules\user\services\user;
use app\lib\Common;
use app\modules\user\models\user\UserModel;
use Yii;
use app\base\BaseService;

class UserService extends BaseService
{
    const SALT_LEN = 10;//密码加盐值数据表中的salt长度<=数据表的字段salt长度
    /**
     * 用户登录服务接口
     * @param $username 用户名
     * @param string $password 密码
     * @param int $type 用户登录来源【1网页版登录，2app端登录】
     * @return array
     */
    public static function UserLogin($username, $password, $type = 1) {
        $isExistUser = self::checkIsExistByUsername($username);
        if(!$isExistUser) {
            return self::returnErrData([], 500, '用户不存在！');
        }
        $password = self::createPwd($password, $isExistUser['salt']);
        if($isExistUser['password'] != $password) {
            return self::returnErrData([], 500, '账号或密码有误！');
        }
        //设置cookie值
        $randChar = Common::getRandChar(self::SALT_LEN);//随机字符串的md5加密值
        $cacheUserInfo = [
            'user_id' => $isExistUser['id'],
            'username' => $isExistUser['username'],
            'session_token' => $randChar,
            'token' => self::createToken($isExistUser['id'], $randChar),
            'app_type' => $type,//用户登录来源
        ];
        $setLoginCookie = self::setLoginCookie($cacheUserInfo);
        $setLoginCookie = json_decode($setLoginCookie, true);
        if(isset($setLoginCookie['code']) && $setLoginCookie['code'] == 0) {
            return self::returnOkData($cacheUserInfo);
        }
        return self::returnErrData([], 500, '系统异常！');
        //如果是单点登录的话
    }
    public static function checkIsExistByUsername() {
        return [
            'salt' => '2WDW5F',
            'user_id' => 664122132213871075,
            'password' => 'wertgfdvdssahgffdsdsds',
        ];
    }
    /**
     * 加密密码生成
     * @param $pwd
     * @param string $salt
     * @return string
     */
    public static function createPwd($pwd, $salt) {
        $pwd_salt = Yii::$app->params['user']['pwd_salt'];
        return md5($pwd.$pwd_salt.$salt);
    }
    /**
     *  生成安全的Token值
     * @param string $uid
     * @param string $token
     * @return string
     */
    public static function createToken($uid = '', $token = '') {
        $seeder = $uid . '|' . $token;
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $seeder .= $_SERVER['HTTP_USER_AGENT'];
        }
        $seeder .= Yii::$app->params['user']['cookieSalt'];
        return md5($seeder);
    }
    /**
     * 设置登陆的时候的cookie.
     * @param $userInfo
     * @return array
     */
    public static function setLoginCookie($userInfo) {
        if (!isset($userInfo['user_id']) || (!isset($userInfo['session_token']))) {
            return BaseService::returnErrData($userInfo, 40004048);
        }
        $user['user_id'] = $userInfo['user_id'];
        $user['session_token'] = $userInfo['session_token'];
        $token = self::createToken($userInfo['user_id'], $user['session_token']);
        $user['token'] = $token;

        $rs = setcookie('cacheUserInfo', json_encode($user), time() + 864000, '/', null, null, true);
        if ($rs) {
            return self::returnOkData($userInfo);
        }
        return self::returnErrData($userInfo, 40004059, '设置cookie失败');
    }
    /**
     * 获取当前cookie登录的用户id
     * @return int
     */
    public static function getUserId() {
        if(isset($_COOKIE['cacheUserInfo']) && !empty($_COOKIE['cacheUserInfo'])) {
            $userInfo = json_decode($_COOKIE['cacheUserInfo'],true);
            $user['user_id'] = $userInfo['user_id'];
            $user['session_token'] = $userInfo['session_token'];
            $token = self::createToken($user['user_id'], $user['session_token']);
            if($token != $user['session_token']) {
                return $user['user_id'];
            }
            return 0;
        }
        return 0;
    }

    /**
     * 获取当前用户信息
     * @param $userid
     * @return array
     */
    public static function getUserInfo($userid) {
        $ret = [
            'code' =>0,
            'data' => [
                'id'=>1,
                'username'=>'jawei',
                'password'=>'12edwewqrfdsew4564frgftewt',
                'salt'=>'Eqesw223',
                'email'=>'gaozhiwei429@sina.com',
                'mobile'=>'15910987706',
                'source'=>'1',
                'last_login_time'=>1345434353,
            ]
        ];
        return self::returnOkData($ret);
    }
}
